<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */

namespace Svick\Http\Client;


use Psr\Http\Message\ResponseInterface;

/**
 * Class Response
 * @package Svick\Http\Client
 * @method ResponseInterface getProtocolVersion()
 * @method ResponseInterface hasHeader($name)
 * @method ResponseInterface getBody()
 */
class Response
{
    /**
     * @var ResponseInterface
     */
    protected $response;

    public function __construct($response)
    {
        $this->response = $response;
    }

    /**
     * 获取单个响应头
     *
     * @param $name
     * @return string
     */
    public function header($name)
    {
        return $this->response->getHeaderLine($name);
    }

    /**
     * 获取所有响应头
     *
     * @return \string[][]
     */
    public function headers()
    {
        return $this->response->getHeaders();
    }

    /**
     * 获取响应体
     *
     * @return string
     */
    public function body()
    {
        return (string) $this->response->getBody();
    }

    /**
     * 获取json_decode之后的响应体
     *
     * @return mixed
     */
    public function json()
    {
        return json_decode($this->body());
    }

    /**
     * 获取json_decode之后的响应体
     *
     * @return mixed
     */
    public function array()
    {
        return json_decode($this->body(), true);
    }

    /**
     * 获取响应状态码
     *
     * @return int
     */
    public function status()
    {
        return (int) $this->response->getStatusCode();
    }

    /**
     * 获取响应的原因短语
     *
     * @return string
     */
    public function reason()
    {
        return $this->response->getReasonPhrase();
    }

    /**
     * 响应是否OK
     *
     * @return bool
     */
    public function ok()
    {
        return $this->status() === 200;
    }

    /**
     * 响应是否成功
     *
     * @return bool
     */
    public function successful()
    {
        return $this->status() >= 200 && $this->status() < 300;
    }

    /**
     * 确定响应是否为重定向
     *
     * @return bool
     */
    public function redirect()
    {
        return $this->status() >= 300 && $this->status() < 400;
    }

    /**
     * 确定响应是否为403禁止响应
     *
     * @return bool
     */
    public function forbidden()
    {
        return $this->status() === 403;
    }

    /**
     * @return bool
     */
    public function failed()
    {
        return $this->serverError() || $this->clientError();
    }

    /**
     * @return bool
     */
    public function clientError()
    {
        return $this->status() >= 400 && $this->status() < 500;
    }

    /**
     * @return bool
     */
    public function serverError()
    {
        return $this->status() >= 500;
    }

    public function __call($name, $arguments)
    {
        return call_user_func_array([$this->response, $name], $arguments);
    }
}
